'use strict';

var jwt = require('jsonwebtoken');
module.exports = app => {
  return class extends app.Controller {
    * applogin(ctx) {
        var wpid=ctx.request.query.wpid;
        var code=ctx.request.query.code;
        var wp=yield ctx.model.Wechat.findById(wpid);


        if(wp.accessToken && wp.accessToken.expireTime);
        var url='https://api.weixin.qq.com/sns/jscode2session?appid='+wp.appId+'&secret='+wp.appSecret+'&js_code='+code+'&grant_type=authorization_code';
        const result =yield ctx.curl(url,{dataType: 'json'});
        var user=yield ctx.model.User.findOne({where:{openid:result.data.openid}});
        if(user){
          user.sessionKey=result.data.session_key;
          user.expiresIn=new Date()+result.data.expires_in;
          user.save();
        }else {
            user=yield ctx.model.User.create({sessionKey:result.data.session_key,expiresIn:new Date()+result.data.expires_in,openid:result.data.openid,wechatId:wpid});
        }
        var token=jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60),
            data: {user:user}
        }, ctx.locals.tokenScrect);

        ctx.body={token:token};
    }
    //admin登陆
    * adminlogin(ctx){
        const userName=ctx.request.body.userName;
        const passWord=ctx.request.body.passWord;
        var admin=yield ctx.model.Admin.findOne({where:{userName:userName,passWord:passWord}});
        if(admin){
            var token=jwt.sign({
                exp: Math.floor(Date.now() / 1000) + (60 * 60),
                data: {admin:admin}
            },ctx.locals.tokenScrect);
            ctx.body={token:token};
        }else{
            ctx.body={
                status:false,
                message:'用户名或密码错误，请重新输入'
            }
        }
    }
  };
};
